<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import Card from '@/views/new-screen/components/card.vue'
import DrawEcharts from '@/components/draw-echarts.vue'
import * as echarts from 'echarts'
import {
  getHouseOverview,
  getHouseSecurity,
  getHouseRent,
} from '../api.js'
import { ElMessage, formatter } from 'element-plus'
import mitter from '@/utils/eventBus'
import { getPie3DOption } from './getPie3DOption.js'


const props = defineProps({
  isExpanded: Boolean,
  activeName: String,
})

const totalBuildingChartRef = ref(null)
const totalAreaChartRef = ref(null)
const houseRentChartRef = ref(null)

const totalBuilding = ref(0)
const totalArea = ref(0)

const getTotalChartOption = ({ list, title }) =>{
  return {
    // backgroundColor: 'transparent',
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c89' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c21' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    color: ['#00dfff', '#f8ea9a', '#00dfff'],
    tooltip: {
      trigger: 'item',
      fontSize: 14,
    },
    legend: {
      top: 'middle',
      left: '50%',
      orient: 'vertical',
      formatter: (name) => {
        return name + '      ' + list.find(item => item.name === name).value + (title.includes('面积') ? '万平' : ' 栋')
      },
      fontSize: 18,
      icon: "circle",
      itemWidth: 10,
      itemHeight: 10,
    },
    series: [
      {
        name: '60%',
        type: 'pie',
        selectedMode: 'single',
        radius: ['35%', '37%'],
        center: ['25%', '50%'],
        label: {
          position: 'inner',
          fontSize: 14
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1548 },
        ]
      },
      {
        name: title,
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['25%', '50%'],
        avoidLabelOverlap: false,
        showBackground: false,
        label: {
          show: true,
          fontSize: 16,
          position: 'center',
          formatter: '{d}%',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
            formatter: '{d}%',
          }
        },
        labelLine: {
          show: false
        },
        data: [...list]
      }
    ]
  }
} 

const getPieChartOption = ({ list, title }) => {
  const total = list.reduce((a, b) => a + b.value, 0)
  return {
    // backgroundColor: 'transparent',
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c89' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c21' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    color: ['#00dfff', '#f8ea9a'],
    tooltip: {
      trigger: 'item',
      fontSize: 14,
    },
    legend: {
      top: 'middle',
      right: '5%',
      orient: 'vertical',
      formatter: (name) => {
        const value = list.find(item => item.name === name).value
        return name + '  ' + value + ' 户 ' + (value / total * 100).toFixed(2) + '%'
      },
      fontSize: 18,
      icon: "circle",
      itemWidth: 10,
      itemHeight: 10,
    },
    series: [
      {
        name: title,
        type: 'pie',
        selectedMode: 'single',
        radius: ['0%', '70%'],
        center: ['20%', '50%'],
        avoidLabelOverlap: false,
        showBackground: false,
        label: {
          show: false,
          fontSize: 16,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [...list]
        // [
        //   { value: 1048, name: 'Search Engine' },
        //   { value: 735, name: 'Direct' },
        //   { value: 580, name: 'Email' },
        //   { value: 484, name: 'Union Ads' },
        //   { value: 300, name: 'Video Ads' }
        // ]
      }
    ]
  };
  return {
    // legend: {
    //   top: 'bottom'
    // },
    // toolbox: {
    //   show: true,
    //   feature: {
    //     mark: { show: true },
    //     dataView: { show: true, readOnly: false },
    //     restore: { show: true },
    //     saveAsImage: { show: true }
    //   }
    // },
    backgroundColor: {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 1,
      y2: 0,
      colorStops: [{
          offset: 0, color: '#01153c89' // 0% 处的颜色
      }, {
          offset: 1, color: '#01153c21' // 100% 处的颜色
      }],
      global: false // 缺省为 false
    },
    color: ['#00dfff', '#f8ea9a'],
    tooltip: {
      trigger: 'item',
      // formatter: '{b} : {c}户 ({d}%)'
      formatter: ' {c}<i>户</i>  ({d}%)<br>{b}'
    },
    series: [
      {
        name: title,
        type: 'pie',
        radius: '65%',
        center: ['50%', '50%'],
        selectedMode: 'single',
        showBackground: false,
        // itemStyle: {
        //   borderRadius: 8
        // },
        data: [...list]
      }
    ],
    backgroundColor: 'transparent'
  }
}

const updateChartHouseOverview = (data) => {
  const list = data.data || []
  // const buildingData = [{ name: '住宅', value: 152192  }, { name: '非住宅', value: 132210  }]
  const buildingData = list.map((e) => ({ name: e.name, value: e.house_num}))
  totalBuildingChartRef.value?.updateOption(getTotalChartOption({ list: buildingData, title: '房屋总栋数' }))

  // const areaData = [{ name: '住宅', value: 24733.55  }, { name: '非住宅', value: 28395.53  }]
  const areaData = list.map((e) => ({ name: e.name, value: e.actual_area}))
  totalAreaChartRef.value?.updateOption(getTotalChartOption({ list: areaData, title: '建筑总面积' }))

  totalBuilding.value = data.houseNum
  totalArea.value = data.houseArea
}

const updateChartHouseRent = (data) => {
  const pieData = [
    {
      name: 'A类家庭户数',
      value: +data['A类家庭户数'][0],
      selected: true,
      itemStyle: {
        opacity: 0.9,
        color: '#00d7e9'
      }
    },
    {
      name: 'B类家庭户数',
      value: +data['B类家庭户数'][0],
      itemStyle: {
        opacity: 0.9,
        color: '#41c1ff'
      }
    }
  ]
  // houseRentChartRef.value?.updateOption(getPieChartOption({ list: pieData, title: '住房保障' }))
  const pie3DOption = getPie3DOption(pieData)
  houseRentChartRef.value?.updateOption(pie3DOption)
}

const rentlist = ref([
  { name: '累计上架', value: 0 },
  { name: '在架房源', value: 0 },
  { name: '预告房源', value: 0 },
  { name: '库存房源', value: 0 },
])

const updateDataHouseRent = (data) => {
  rentlist.value = []
  Object.entries(data).forEach((item) => {
    const [key, value] = item
    if (key !== '下架房源') {
      rentlist.value.push({ name: key, value })
    }
  })
}

// watch(
//   () => props.activeName,
//   (val) => {
//     if (val) {
//       updateTotalData()
//     }
//   },
// )
const reqData = () => {
  Promise.all([
    getHouseOverview(),
    getHouseSecurity(),
    getHouseRent(),
  ]).then(([houseOverview, houseSecurity, houseRent]) => {
    console.log('houseOverview', houseOverview)
    console.log('houseSecurity', houseSecurity)
    console.log('houseRent', houseRent)
    if (houseOverview.success) {
      updateChartHouseOverview(houseOverview.data)
    }
    if (houseSecurity.success) {
      updateChartHouseRent(houseSecurity.data)
    }

    if (houseRent.success) {
      updateDataHouseRent(houseRent.data)
    }
  })
}

onMounted(() => {
  reqData()
  // setTimeout(() => {
  //   updateTotalData()
  // }, 300)
})

onUnmounted(() => {})
</script>

<template>
  <div :class="['left', isExpanded ? 'active' : '']">
    <card name="房屋总览" class="house-total">
      <div class="total-buildings">
        <div class="total-head head">
          <span class="head-title">房屋总栋数</span>
          <span class="head-value">
            <span class="value">{{ totalBuilding }}</span>
            <span class="unit">栋</span>
          </span>
        </div>
        <div class="chart">
          <draw-echarts
            ref="totalBuildingChartRef"
            width="420"
            height="140"
            :options="{}"
          ></draw-echarts>
        </div>
      </div>
      <div class="total-area">
        <div class="head">
          <span class="head-title">建筑总面积</span>
          <span class="head-value">
            <span class="value">{{ totalArea }}</span>
            <span class="unit">万平</span>
          </span>
        </div>
        <div class="chart">
          <draw-echarts
            ref="totalAreaChartRef"
            width="420"
            height="140"
            :options="{}"
          ></draw-echarts>
        </div>
      </div>
    </card>
    <card name="住房保障" class="house-security">
      <div class="chart">
        <draw-echarts
          ref="houseRentChartRef"
          width="420"
          height="180"
          :options="{}"
        ></draw-echarts>
      </div>
    </card>
    <card name="住房租赁" class="house-rent">
      <div class="flex">
        <div class="box" v-for="(item, i) in rentlist" :key="i">
          <div class="box-title">{{ item.name }}</div>
          <div class="box-value">
            <span class="value">{{ item.value }}</span>
            <span class="unit">
              套
            </span>
          </div>
        </div>
      </div>
    </card>
  </div>
</template>

<style scoped lang="scss">
.left {
  .title-icon {
    display: inline-flex;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 61px;
    position: relative;
    bottom: 20px;
    // margin-top: 10px;
  }

  .house-total {
    height: 400px;
    margin-bottom: var(--card-margin-bottom);

    .head {
      background: linear-gradient(90deg, #1f3158 0%, #01153c 100%);
      width: 100%;
      height: 40px;
      line-height: 40px;
      display: flex;
      justify-content: space-between;
      color: #ffffff;

      .head-title {
        font-family: Source Han Sans SC;
        font-weight: 500;
        font-size: 16px;
        margin-left: 16px;
      }

      .head-value {
        font-family: Source Han Sans SC;
        font-weight: 500;
        font-size: 16px;
        margin-right: 10px;
        .value {
          font-size: 18px;
          color: #5db1ed;
        }
        .unit {
          font-size: 14px;
          margin-left: 10px;
        }
      }
    }

  }

  .house-security {
    height: 220px;
    margin-bottom: var(--card-margin-bottom);
  }

  .house-rent {
    height: 315px;

    .flex{
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;

      .box {
        width: 40%;
        height: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;
        color: #bbdbf6;
        // background: linear-gradient(90deg, #072f59 0%, #08062f 100%);
        background-image: url('@/assets/imgs/house_rent_bg.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;
        .box-title { 
          text-align: center;
          margin-bottom: 10px;
        }
        .box-value { 
          text-align: center;
          .value { 
            font-size: 24px;
            font-weight: bold;
            color: #f9fdff;
          }
          .unit { 
            font-size: 16px;
            color: #9eb2d5;
          }
        }

      }
    }
  }
}
</style>
